from sys import stderr
import os

from utils.namespace import Namespace


def log(message):
    stderr.write(message)
    
    
def affirm_dir(dirpath, *components):
    if len(components) > 0:
        dirpath = os.path.join(dirpath, *components)
    if not os.path.isdir(dirpath):
        os.makedirs(dirpath)
        return True, dirpath
    return False, dirpath
    
    
def param_combinations(param_list):
    """An iterator over every combination of the given parameter list. A parameter list has the 
    format [Param], where Param is a pair (param_name, [param_value])."""
    for assignment in _param_combinations(param_list, {}):
        yield Namespace(assignment)
        
        
def _param_combinations(param_list, assignment):
    if len(assignment) == len(param_list):
        yield assignment
    else:
        param, values = param_list[len(assignment)]
        for value in values:
            assignment[param] = value
            for _ in _param_combinations(param_list, assignment):
                yield assignment
            del assignment[param]
            
            
def sample(name, *args):
    """This function creates a new function that takes an RNG as its single argument and returns 
    an observation from the specified probability distribution."""
    def distr(rng):
        return getattr(rng, name)(*args)
    distr.__name__ = "%s{%s}" % (name, ",".join(str(arg) for arg in args))
    return distr
    
    